package com.emath;

import java.text.DecimalFormat;
import org.json.JSONException;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Debug;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.emath.activities.GamePlay;
import com.emath.objects.Game;
import com.emath.objects.OpponentPlayer;
import com.emath.objects.Player;
import com.emath.objects.Username;
import com.emath.shared.Globals;
import com.emath.shared.RestClient;
import com.lnl.R;

public class ConnecttoPlayer extends FragmentActivity {
	private Connecting task;
	private String online = "";
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.connect);

		// Typeface tf =
		// Typeface.createFromAsset(getAssets(),"fonts/Capture_it.ttf");

		// TextView editText = (TextView) findViewById(R.id.EnterPlayer);
		// editText.setTypeface(tf);

		final Button connect = (Button) findViewById(R.id.button_send);
		// connect.setTypeface(tf);
		connect.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				task = new Connecting();
				task.execute(getApplicationContext());

			}
		});
	}
	private void handleonbackbutton() {
		task.cancel(true);
	}

	public class Connecting extends AsyncTask<Context, Void, Context> {
		ProgressDialog dialog;
		RestClient Connect = new RestClient();
		
		protected Context doInBackground(Context... Contexts) {
			EditText player2username = (EditText) findViewById(R.id.edit_message);
			String checkOnline = "http://emath-project.appspot.com/emath/emathservicehttp?function=getuser&userID="
					+ player2username.getText().toString();
			Connect.connect(checkOnline);
			if (Globals.isconnected== 0){
				this.cancel(true);
				Toast.makeText(ConnecttoPlayer.this, "Connection Error", Toast.LENGTH_LONG).show();
			}
			if (this.isCancelled()) {
				dialog.dismiss();
				return Contexts[0];
			}
			int index = Connect.findindex("online");

			try {
				online = Connect.getvalArray().getString(index);
			} catch (JSONException e) {
				e.printStackTrace();
			}
			if (!online.equals("true")) {

				Connect.clear();
				return Contexts[0];
			}
			String creategame = "http://emath-project.appspot.com/emath/emathservicehttp?function=startgame&user1="
					+ Username.getUser()
					+ "&user2="
					+ player2username.getText().toString();
			Connect.connect(creategame);
			if (Globals.isconnected== 0){
				this.cancel(true);
				Toast.makeText(ConnecttoPlayer.this, "Hello World", Toast.LENGTH_LONG).show();
			}
			index = Connect.findindex("gameID");
			String id = null;
			try {
				id = Connect.getvalArray().getString(index);
			} catch (JSONException e) {
				e.printStackTrace();
			}
			Game.setGameID(id);
			Connect.clear();
			String isconnected = "http://emath-project.appspot.com/emath/emathservicehttp?function=getgame&gameID="
					+ id;
			Connect.connect(isconnected);
			if (Globals.isconnected== 0){
				this.cancel(true);
				Toast.makeText(ConnecttoPlayer.this, "Hello World", Toast.LENGTH_LONG).show();
			}
			int checkconnect = Connect.findindex("round");
			Connect.clear();
			while (true) {
				if (task.isCancelled()) {
					String endround = "http://emath-project.appspot.com/emath/emathservicehttp?function=setgame&gameID="
							+ id + "&round=finished";
					Connect.connect(endround);
					String endgame = "http://emath-project.appspot.com/emath/emathservicehttp?function=endgame&gameID="
							+ id;
					Connect.connect(endgame);

					return Contexts[0];
				}
				Connect.connect(isconnected);
				if (Globals.isconnected== 0){
					this.cancel(true);
					Toast.makeText(ConnecttoPlayer.this, "Hello World", Toast.LENGTH_LONG).show();
				}
				try {
					if (Connect.getvalArray().getString(checkconnect)
							.equals("pregame")
							|| Connect.getvalArray().getString(checkconnect)
									.equals("ingame"))
						break;
				} catch (JSONException e) {
					e.printStackTrace();
				}
				Connect.clear();
			}
			Connect.clear();
			return Contexts[0];

		}

		protected void onPreExecute() {
			logHeap();
			// do your work here
			InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

			inputManager.hideSoftInputFromWindow(getCurrentFocus()
					.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
			dialog = new ProgressDialog(ConnecttoPlayer.this);
			dialog.setMessage("Waiting");
			dialog.setCancelable(false);
			dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							task.cancel(true);
							dialog.dismiss();

						}
					});
			dialog.show();

		}
		protected void onPostExecute(Context result) {
			if (this.isCancelled())
				return;

			if (online.equals("true")) {
				try {
					dialog.dismiss();
					dialog = null;
				} catch (Exception e) {
					// nothing
				}
				logHeap();
				Player.setPlayer("p1");
				OpponentPlayer.setPlayer("p2");
				Game.setCreatedgame(true);
				Intent intent = new Intent(result, GamePlay.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				startActivity(intent);
				finish();
			} else {
				dialog.dismiss();
				runOnUiThread(new Runnable() {
					public void run() {

						Toast tooltip = Toast.makeText(ConnecttoPlayer.this,
								"That user is not online.", Toast.LENGTH_LONG);
						tooltip.setGravity(Gravity.TOP
								| Gravity.CENTER_HORIZONTAL, 0, 200);
						tooltip.show();
					}
				});
			}
		}
	}
	public static void logHeap() {
		Double allocated = new Double(Debug.getNativeHeapAllocatedSize())
				/ new Double((1048576));
		Double available = new Double(Debug.getNativeHeapSize()) / 1048576.0;
		Double free = new Double(Debug.getNativeHeapFreeSize()) / 1048576.0;
		DecimalFormat df = new DecimalFormat();
		df.setMaximumFractionDigits(2);
		df.setMinimumFractionDigits(2);
		Runtime rt = Runtime.getRuntime();
		long maxMemory = rt.maxMemory();
		Log.v("memory2", "maxMemory:" + Long.toString(maxMemory));
		Log.e("memory2", "debug. =================================");
		Log.e("memory2", "debug.heap native: allocated " + df.format(allocated)
				+ "MB of " + df.format(available) + "MB (" + df.format(free)
				+ "MB free)");
		Log.e("memory2",
				"debug.memory: allocated: "
						+ df.format(new Double(Runtime.getRuntime()
								.totalMemory() / 1048576))
						+ "MB of "
						+ df.format(new Double(
								Runtime.getRuntime().maxMemory() / 1048576))
						+ "MB ("
						+ df.format(new Double(Runtime.getRuntime()
								.freeMemory() / 1048576)) + "MB free)");
	}
	public void displayhelp() {

		HelpDialog helpDialog = new HelpDialog(ConnecttoPlayer.this);
		helpDialog.setTitle("Help contents");
		helpDialog.show();
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.ingamemenu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.exit:
			RestClient Connect = new RestClient();
			final MediaPlayer buttonSound = MediaPlayer.create(
					ConnecttoPlayer.this, R.raw.button_click);
			buttonSound.start();
			String logout = "http://emath-project.appspot.com/emath/emathservicehttp?function=logout&userID="
					+ Username.getUser();
			Connect.connect(logout);
			Connect.clear();
			finish();
			return true;
		case R.id.help:
			displayhelp();
			return true;
		}
		return super.onOptionsItemSelected(item);

	}

	@Override
	protected void onPostResume() {
		if (Globals.focusedActivity.equals("ConnecttoPlayer")) {
			if (Globals.settingsHolder[1] == 1) {
				startService(Globals.backgroundMusicService);
			}
			Globals.isMusicPlaying = true;
		}
		super.onPostResume();
	}

	@Override
	protected void onPause() {
		if (this.isFinishing()) {
			Globals.focusedActivity = "GameMenu";
		} else {
			if (Globals.settingsHolder[1] == 1) {
				stopService(Globals.backgroundMusicService);
			}
			Globals.isMusicPlaying = false;
		}
		super.onPause();
	}
}
